<html>
    <head>
        <title>js event</title>
    </head>
    <body>
        <div id="div1" onclick="addButton1()" style="background-color:greenyellow; width:500px; height: 500px">
        
        </div>
    </body>
</html>

<script>
    function addButton() {
        var but1 = document.createElement("button");
        but1.style.width = "50px";
        but1.style.height = "80px";
        but1.style.backgroundColor = "gray";
        //直接运行showValue
        //1
        // but1.onclick = showValue("hah");
        //2
        // but1.addEventListener('click', showValue());
        
        var a = 'ddd';
        //不会直接运行
        //1
        // but1.onclick = function() {
        //     showValue(a)
        // }
        //2
        // but1.onclick = showValue;
        //3
        // but1.addEventListener('click', function(){showValue()});
        //4
        // but1.addEventListener('click', showValue);
        // a = 'aaa';
        //不设置attribute 在浏览器控制台Elements中看不到onclick(attribute与property的区别)
        but1.setAttribute("onclick", "showValue('"+a+"')");

        var div1 = document.getElementById("div1");
        
        div1.appendChild(but1);
    }

    function addButton1() {
        var but = '<button style="width:50px; height:50px;" onclick=\'showValue("haha")\'>点击</button';
            var div1 = document.getElementById("div1");

            div1.innerHTML = but;
    }

    function showValue(str) {
        alert(str);
    }
    addButton();
</script>